package org.smart4j.aopdemo.custom;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 创建一个Proxy工厂来创建Proxy
 */
public class ProxyManager {

    //被代理的目标类
    private Class<?> targetClass;

    //代理类列表
    private List<Proxy> proxyList;

    public ProxyManager(Class<?> targetClass, List<Proxy> proxyList) {
        this.targetClass = targetClass;
        this.proxyList = proxyList;
    }

    @SuppressWarnings("unchecked")
        public <T> T createProxy(){
        return (T) Enhancer.create(targetClass, new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                ProxyChain proxyChain = new ProxyChain(proxyList,targetClass,o,method,objects,methodProxy);
                //执行链条,开启链式反应
                proxyChain.doProxyChain();
                //返回原方法调用的结果
                return proxyChain.getMethodResult();
            }
        });
    }

}
